from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class boxcox(OWRpy): 
    globalSettingsList = ['commit']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.setRvariableNames(["txt"])
        self.data = {}
         
        self.RFunctionParam_object = ''
        self.inputs.addInput('id0', _('R Variable Object'), signals.base.RDataFrame, self.processobject)
        self.outputs.addOutput('id0', 'Box-Cox transformation', signals.base.RMatrix)
        
        area = redRGUI.base.widgetBox(self.controlArea,orientation='vertical')  
        options = redRGUI.base.widgetBox(area,orientation='horizontal')
 
        self.namesList = redRGUI.base.listBox(options, label = _('Select element'))
        self.namesList.setSelectionMode(QAbstractItemView.SingleSelection)

        self.lambdaParam = redRGUI.base.lineEdit(area, label = "Lambda:", text = '1')		
		
        self.methodButtons = redRGUI.base.radioButtons(options,  label = "Transformation type", 
        buttons = [('Box-Cox'),
        ('Yeo-Johnson'),
        ('Simple power')],
        setChecked='Box-Cox',orientation='vertical')

        self.adjButtons = redRGUI.base.radioButtons(options,  label = "Normalized for Jacobian = 1", 
        buttons = [('TRUE'),('FALSE')],
        setChecked='FALSE',orientation='vertical')
        
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True)
        self.RoutputWindow = redRGUI.base.textEdit(self.controlArea, label = _("RoutputWindow"))
        
    def processobject(self, data):
        if not self.require_librarys(["car"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if not self.require_librarys(["nortest"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_object=data.getData()
            self.data = data
            if self.R('names('+self.RFunctionParam_object+')') == []:
                listBox.update(range(self.R('ncol('+self.RFunctionParam_object+')')))
            else:
                self.namesList.update(self.R('names('+self.RFunctionParam_object+')', wantType = 'list'))
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_object=''
    def commitFunction(self):
        
        if unicode(self.RFunctionParam_object) == '': return
        if len(self.namesList.selectedItems()) == 0: return # must select a column.
    
        if 'Box-Cox' in self.methodButtons.getChecked(): self.powTrans='bcPower'
        if 'Yeo-Johnson' in self.methodButtons.getChecked(): self.powTrans='yjPower'
        if 'Simple power' in self.methodButtons.getChecked(): self.powTrans='basicPower'
        if 'TRUE' in self.adjButtons.getChecked(): self.jacAdj='TRUE'
        if 'FALSE' in self.adjButtons.getChecked(): self.jacAdj='FALSE'
        
        self.R('rSelected<-'+unicode(self.RFunctionParam_object)+'[,'+unicode(self.namesList.row(self.namesList.currentItem())+1)+']')

        self.R(self.Rvariables['txt']+'<-'+self.powTrans+'(U=rSelected, lambda='+str(self.lambdaParam.text())+', jacobian.adjusted='+self.jacAdj+')')         
        self.newData = signals.base.RMatrix(self, data = self.Rvariables["txt"])
        self.rSend("id0", self.newData)
        
        self.R('normality<-ad.test(x='+self.Rvariables['txt']+')') 
        self.RoutputWindow.clear()
        tmp = self.R('paste("<u>Data name</u>: ", normality$data.name,"\n", "<u>Method</u>: ",normality$method,"\n", "<u>Test statistic</u>: ", normality$statistic,"\n","<u>p-value</u>: ", normality$p.value, collapse ="\n")')
        self.RoutputWindow.insertHtml('<br><pre>'+tmp+'</pre>')
        